How to use| operator in Javascript
Another approach is to explicitly define the properties as either the expected type or undefined within the interface. This indicates that the property can either have a valid value or value is absent.
Syntax:
property name: data type | undefined
Example: This example shows the use of | operator for creating an optional property.
Javascript
interface UserInfo { username: string; email: string; age: number | undefined; } const user: UserInfo = { username: "sandeep" , email: "sandeep@example.com" , age: undefined, // Optional property }; console.log(user.age); |
Output:
undefined
How to Create an Interface with Optional Property ?
In TypeScript interfaces play a crucial role in defining the structure of objects. One of the powerful features is the ability to specify optional properties within an interface. It allows developers to create flexible structures that can be helpful in various scenarios. In this article, we will explore how to create interfaces with optional properties in TypeScript and understand when and why this feature is useful.
Table of Content
- Using the “?” operator
- Using | operator
- Utilizing Partial Interface
Contact Us